/**
 * 
 */
package com.hezhi.trafficcopsys.persistence.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hezhi.framework.dao.BaseDaoImpl;
import com.hezhi.framework.dao.DAOUtil;
import com.hezhi.framework.dao.common.Extractor;
import com.hezhi.framework.exception.DaoException;
import com.hezhi.trafficcopsys.domain.User;
import com.hezhi.trafficcopsys.persistence.dao.UserDao;

/**
 * @author tony
 * 
 */
public class UserDaoImpl  extends BaseDaoImpl implements UserDao{
	
	   /**
	 * 
	 */
	private static final long serialVersionUID = -8013560469607424201L;
	
	/**
     * Logging output for this user database instance.
     */
    private Log log = LogFactory.getLog(this.getClass());
    
    
    public UserDaoImpl() {
    	
    	Connection conn = null;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String createTblSql = "create table IF NOT EXISTS users (username string, password string,privilege string,filepath string);";
	        this.createTable(conn, createTblSql);
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
    }
	
    /**
     * <p>Create and return a new {@link User} defined in this user database.
     * </p>
     *
     * @param username Username of the new user
     *
     * @exception IllegalArgumentExceptionif the specified username
     *  is not unique
     */
	@Override
    public int addUser(User user) {
		Connection conn = null;
		int intAddNums = 0;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "insert into users (username,password,privilege,filepath) values(?,?,?,?)";
	        intAddNums = this.execute(conn, sql, new Object[]{user.getUsername(),user.getPassword(),user.getPrivilege(),user.getFilepath()});
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
			intAddNums = 0;
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
        return intAddNums;
    }

	@Override
	public int delUser(String[] usernames) {
		Connection conn = null;
		int intAddNums = 0;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        StringBuffer delSqlBuffer = new StringBuffer ();
	        for( int i = 0; i < usernames.length; i++){
	        	if( i == 0){
	        		delSqlBuffer.append("delete from users where username in (");
	        	}
	        	
	        	delSqlBuffer.append("?");
	        	if( i == usernames.length-1){
	        		delSqlBuffer.append(")");
	        	} else {
	        		delSqlBuffer.append(",");
	        	}
	        }
	        if( delSqlBuffer.length() > 0){
	        	intAddNums = this.execute(conn, delSqlBuffer.toString(), usernames);
	        }
		} catch (DaoException e) {
			log.error(e.getMessage());
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
        return intAddNums;
	}

	@Override
	public List<User> getAllUser() {
		List<User> listUsers = new ArrayList<User>();
		Connection conn = null;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "select * from users";
	        listUsers = this.list(conn, sql, new Extractor<User>(){
	        	@Override
				public User extract(ResultSet rs)
					throws SQLException {
	        		User user = new User();
	        		user.setUsername(rs.getString("username"));
	        		user.setPassword(rs.getString("password"));
	        		user.setPrivilege(rs.getString("privilege"));
	        		user.setFilepath(rs.getString("filepath"));
	        		return user;
	        	}
	        });
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
		return listUsers;
	}
	
	@Override
	public List<User> listUserByPage(int pageSize, int pageNo) {
		List<User> listUsers = new ArrayList<User>();
		Connection conn = null;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "select * from users limit " + pageSize + " offset " + (pageNo - 1) * pageSize;
	        listUsers = this.list(conn, sql, new Extractor<User>(){
	        	@Override
				public User extract(ResultSet rs)
					throws SQLException {
	        		User user = new User();
	        		user.setUsername(rs.getString("username"));
	        		user.setPassword(rs.getString("password"));
	        		user.setPrivilege(rs.getString("privilege"));
	        		user.setFilepath(rs.getString("filepath"));
	        		return user;
	        	}
	        });
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
		return listUsers;
	}

	@Override
	public User getUser(String username) {
		User user = null;
		Connection conn = null;;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "select * from users";
	        user = this.get(conn, sql, new Extractor<User>(){
	        	@Override
				public User extract(ResultSet rs)
					throws SQLException {
	        		User user = new User();
	        		user.setUsername(rs.getString("username"));
	        		user.setPassword(rs.getString("password"));
	        		user.setPrivilege(rs.getString("privilege"));
	        		user.setFilepath(rs.getString("filepath"));
	        		return user;
	        	}
	        });
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
		return user;
	}

	@Override
	public int editUser(User user) {
		Connection conn = null;
		int intAddNums = 0;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "update  users set password = ? where username = ? ";
	        intAddNums = this.execute(conn, sql, new Object[]{user.getPassword(),user.getUsername()});
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
			intAddNums = 0;
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
        return intAddNums;
	}
	
	public int getTotalSize(){

		Connection conn = null;
		int intAddNums = 0;
		try {
			conn = DAOUtil.getSQLiteDBConnection();
			
	        String sql = "select count(*) from users";
	        intAddNums = this.get(conn, sql, new Extractor<Integer>(){
	        	@Override
				public Integer extract(ResultSet rs)
					throws SQLException {
	        		return rs.getInt(1);
	        	}
	        });
	        
		} catch (DaoException e) {
			log.error(e.getMessage());
			intAddNums = 0;
		} finally {
			DAOUtil.closeJDBCConnection(conn);
		}
        return intAddNums;
	
	}
}
